package com.etpjava.dao.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.etpjava.dao.EmployeeDao;
import com.etpjava.model.Employee;
import com.etpjava.util.GetSth;
import com.etpjava.util.Page;

/**
 * EmployeeDaoImpl
 * @author liuk
 * @version 0.0.1
 * 
 */
public class EmployeeDaoImpl implements EmployeeDao {
	//static Log logger = LogFactory.getLog(EmployeeDaoImpl.class);
	//log4j 
	Logger logger=Logger.getLogger(EmployeeDaoImpl.class);

	public List<Employee> findAll() {
		return null;
	}

	 public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	private SessionFactory sessionFactory;
	    public void setSessionFactory(SessionFactory sessionFactory) {
	        this.sessionFactory = sessionFactory;
	    }
	public Session getSession() {
		return this.sessionFactory.openSession();
	}

	@Override
	public void delete(Employee em) {
		Session session = this.getSession();
		session.beginTransaction();
		em.setMyeDepartment(null);
		session.delete(em);
		session.getTransaction().commit();

		session.close();

	}

	@Override
	public boolean save(Employee em) {
		Session session = this.getSession();
		session.beginTransaction();
		try {
			session.save(em);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			session.getTransaction().rollback();
			return false;
		} finally {
			session.close();
		}
		return true;
	}

	@Override
	public void update(Employee em) {
		Session session = this.getSession();
		session.beginTransaction();
		try {
			session.update(em);
			session.getTransaction().commit();
		} catch (HibernateException e) {
			session.getTransaction().rollback();
		} finally {
			session.close();

		}
	}

	@Override
	public Employee findById(int id) {
		Employee employee = null;
		Session session = this.getSession();
		session.beginTransaction();
		employee = (Employee) session.get(Employee.class, id);
		logger.info(employee);
		session.close();
		return employee;
	}

	@Override
	public void findByName(Page p, String name) {

		Session session = this.getSession();
		session.beginTransaction();
		String sql = "from Employee where name like ?";
		Query query2 = session.createQuery(sql).setString(0, "%" + name + "%");
		int rowcount = query2.list().size();
		p.setRowTotalCount(rowcount);
		Query query = session.createQuery(sql).setString(0, "%" + name + "%");

		query.setFirstResult(p.getRowStartCount());
		query.setMaxResults(Page.pagesize);
		p.setList(query.list());
		session.getTransaction().commit();
		session.close();

	}


	@Override
	public List<Employee> findByPhone(String phone) {
		Session session = this.getSession();
		session.beginTransaction();
		String sql = "from Employee where telphone like ?";
		System.out.print(phone);
		Query query = session.createQuery(sql).setString(0, phone);
		session.getTransaction().commit();
		@SuppressWarnings("unchecked")
		List<Employee> ems = (List<Employee>) query.list();
		session.close();
		return ems;
	}

	
	public void search(Page p, Map<String, String> sw) {
		Session session = this.getSession();
		session.beginTransaction();
		StringBuilder sws = new StringBuilder();
		if (null != sw.get("minid")) {
			sws.append(" id  >= " + sw.get("minid") + " and ");
		}
		if (sw.get("maxid") != null && !sw.get("maxid").isEmpty()) {
			sws.append(" id  <= " + sw.get("maxid") + " and ");
		}

		if (!sw.get("sname").isEmpty()) {
			sws.append(" name like " + "'%" + sw.get("sname") + "%'" + " and ");

		}

		if (!sw.get("sminage").isEmpty()) {
			sws.append(" birthday <= " + "'"
					+ GetSth.getDate(Integer.parseInt(sw.get("sminage"))) + "'"
					+ " and ");

		}
		if (!sw.get("smaxage").isEmpty()) {
			sws.append(" birthday >= " + "'"
					+ GetSth.getDate(Integer.parseInt(sw.get("smaxage"))) + "'"
					+ " and ");
		}

		if (!sw.get("sdiv").isEmpty()) {
			sws.append(" myeDepartment_id = "
					+ Integer.parseInt(sw.get("sdiv")) + " and ");
		}

		if (!sw.get("sedu").isEmpty()) {
			sws.append(" education like " + "'%" + sw.get("sedu") + "%'"
					+ " and ");
		}
		if (!sw.get("sworkty").isEmpty()) {
			sws.append(" workType like " + "'%" + sw.get("sworkty") + "%'"
					+ " and ");
		}
		if (!sw.get("sworkys").isEmpty()) {
			sws.append(" firstWorkTime <= " + "'"
					+ GetSth.getDate(Integer.parseInt(sw.get("sworkys"))) + "'"
					+ " and ");
		}
		String sql = null;
		String sql2 = null;
		if (sws.toString().indexOf("and") == -1) {
			sql = "from Employee";
			sql2 = "select count(em.id) from Employee em";
		} else {
			int kk = sws.lastIndexOf("and");
			sql = "from Employee where" + sws.subSequence(0, kk);
			sql2 = "select count(em.id) from Employee em where"
					+ sws.subSequence(0, kk);
		}
		logger.info(sql);
		Query query = session.createQuery(sql2);
		int rowc = ((Long) query.list().get(0)).intValue();
		p.setRowTotalCount(rowc);
		Query query2 = session.createQuery(sql);
		query2.setFirstResult(p.getRowStartCount());
		query2.setMaxResults(Page.pagesize);
		session.getTransaction().commit();
		@SuppressWarnings("unchecked")
		List<Employee> ems = (List<Employee>) query2.list();
		p.setList(ems);
		session.close();
	}

	public void findAll(Page aPage) {
		Session session = this.getSession();
		session.beginTransaction();
		int rowcount =((Long) session.createQuery("select count(id) from Employee").list().get(0)).intValue();
		aPage.setRowTotalCount(rowcount);
		String sql = "select em from Employee em";
		Query query = session.createQuery(sql)
				.setFirstResult(aPage.getRowStartCount())
				.setMaxResults(Page.pagesize);
		session.getTransaction().commit();
		aPage.setList(query.list());
		session.close();
	}
	
	/*
	 * @Override public void search(Page p, Map<String, String> sw) {
	 * DetachedCriteria dc = DetachedCriteria.forClass(Employee.class,"em"); if
	 * (!sw.get("sminage").isEmpty()) { dc.add(Restrictions.ge("birthday",
	 * sw.get("time")));
	 * 
	 * } if (!sw.get("smaxage").isEmpty()) { logger.info("blue" +
	 * sw.get("minid")); dc.add(Restrictions.le("birthday", sw.get("time"))); }
	 * if (null != sw.get("minid")) { logger.info("blue" + sw.get("minid"));
	 * dc.add(Restrictions.gt("id", Integer.parseInt(sw.get("minid")))); } if
	 * (sw.get("maxid") != null && !sw.get("maxid").isEmpty()) {
	 * dc.add(Restrictions.lt("id", Integer.parseInt(sw.get("maxid")))); }
	 * 
	 * if (!sw.get("sedu").isEmpty()) { dc.add(Restrictions.like("education",
	 * sw.get("sedu"))); } if (!sw.get("sworkty").isEmpty()) {
	 * dc.add(Restrictions.like("workType", sw.get("sworkty"))); } if
	 * (!sw.get("sworkys").isEmpty()) { //
	 * dc.add(Restrictions.eq("firstWorkTime"
	 * ,GetSth.getNewDate((sw.get("sworkys")))));
	 * 
	 * dc.add(Restrictions.sqlRestriction("firstWorkTime >=?",sw.get("sworkys"),
	 * StandardBasicTypes.DATE)); } if (!sw.get("sdiv").isEmpty()) {
	 * //dc.add(Restrictions.eq("myeDepartment",
	 * Integer.parseInt(sw.get("sdiv")))); //dc.setFetchMode("myeDepartment",
	 * FetchMode.SELECT);
	 * dc.add(Restrictions.sqlRestriction("myeDepartment_id=?"
	 * ,Integer.parseInt(sw.get("sdiv")),StandardBasicTypes.INTEGER)); } Session
	 * session = this.getSession(); session.beginTransaction(); logger.info(sw);
	 * Criteria criteria = dc.getExecutableCriteria(session); CriteriaImpl impl
	 * = (CriteriaImpl) criteria; // 先把Projection取出来 Projection projection =
	 * impl.getProjection(); //获取结果行数 Long rowc = (Long)
	 * criteria.setProjection(Projections.rowCount()) .uniqueResult();
	 * logger.info(rowc); //设置到page p.setRowTotalCount(rowc.intValue()); //
	 * 设置Projection criteria.setProjection(projection); logger.info(projection);
	 * if (projection == null) { //返回对象
	 * criteria.setResultTransformer(CriteriaSpecification.ROOT_ENTITY); } List
	 * list = criteria.setFirstResult(p.getRowStartCount())
	 * .setMaxResults(p.pagesize).list(); p.setList(list); logger.info(list);
	 * session.getTransaction().commit(); session.close(); }
	 */

}
